package com.async.Hander;

import com.async.entity.Student;
import com.async.mapper.StudentMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

@Slf4j
@Component
public class SyncStudentHandler {

    @Autowired
    private StudentMapper studentMapper;


    @Async(value = "col")
    public Future<String> syncSaveStudents(List<Student> studentList, int pageIndex) {
        long startTime = System.currentTimeMillis();
        System.out.println("thread name " + Thread.currentThread().getName());
        log.info(String.format("此批数据的段数为:%s 此段数据的数据条数为:%s", pageIndex, studentList.size()));
        //声明future对象
        Future<String> result = new AsyncResult<String>("");
        //循环遍历该段旅客集合
        try {
            //数据入库操作
            studentMapper.saveStudent(studentList);
        } catch (Exception e) {
            //记录出现异常的时间，线程name
            result = new AsyncResult<String>("fail,time=" + System.currentTimeMillis() + ",thread id=" + Thread.currentThread().getName() + ",pageIndex=" + pageIndex);
        }
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime + "," + Thread.currentThread().getName());
        return result;
    }


    @Async(value = "col")
    public Future<List<Student>> syncSelectStudents(int start, int end, int i) {
        System.out.println("start:" + start + ",end:" + end);
        long startTime = System.currentTimeMillis();
        System.out.println("thread name " + Thread.currentThread().getName());
//        log.info(String.format("此批数据的段数为:%s 此段数据的数据条数为:%s", pageIndex, studentList.size()));
        //声明future对象
        List<Student> students = new ArrayList<>();
        try {
            //数据入库操作
            students = studentMapper.studentListByLimit(start, end);
        } catch (Exception e) {
            //记录出现异常的时间，线程name
//            result = new AsyncResult  <List<Student>>("fail,time=" + System.currentTimeMillis() + ",thread id=" + Thread.currentThread().getName() + ",pageIndex=" + i);
        }
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime + "," + Thread.currentThread().getName());
        return new AsyncResult<List<Student>>(students);
    }
}
